package com.example.mystore.controller;

import com.example.mystore.model.CartItem;
import com.example.mystore.model.User;
import com.example.mystore.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    // 添加商品到购物车
    @PostMapping("/add")
    public ResponseEntity<?> addToCart(@RequestParam Long userId, @RequestParam Long productId, @RequestParam int quantity) {
        cartService.addToCart(userId, productId, quantity);
        return ResponseEntity.ok().body("商品已添加到购物车");
    }

    // 获取购物车商品列表
    @GetMapping
    public List<CartItem> getCartItems(@RequestParam Long userId) {
        return cartService.getCartItems(userId);
    }

    // 更新购物车商品数量
    @PutMapping("/update/{itemId}")
    public ResponseEntity<?> updateCartItem(@PathVariable Long itemId, @RequestParam int quantity) {
        cartService.updateCartItem(itemId, quantity);
        return ResponseEntity.ok().body("购物车商品数量已更新");
    }

    // 删除购物车商品
    @DeleteMapping("/delete/{itemId}")
    public ResponseEntity<?> deleteCartItem(@PathVariable Long itemId) {
        cartService.deleteCartItem(itemId);
        return ResponseEntity.ok().body("商品已从购物车中删除");
    }

    // 结算购物车，生成订单
    @PostMapping("/checkout")
    public ResponseEntity<?> checkout(@RequestParam Long userId) {
        cartService.checkout(userId);
        return ResponseEntity.ok().body("订单已生成");
    }

    // 获取当前登录用户（简化版）
    private User getCurrentUser() {
        // 实际项目中应从请求头中的令牌获取用户信息
        return new User(1L, "testuser", "password", "test@example.com");
    }
}